package com.floatroot;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.FrameLayout;

public class FloatView {
	private ViewGroup mParentVG;
	private View rootView;

	public FloatView(View view, int resId) {
		//1.找到帧布局
		mParentVG = findRootParent(view);
		//2.渲染菜单布局
		rootView = LayoutInflater.from(view.getContext()).inflate(resId, null, false);


	}

	private ViewGroup findRootParent(View view) {
		//		((Activity)view.getContext()).getWindow().getDecorView().findViewById(android.R.id.content);
		do{
			if(view instanceof FrameLayout){
				if(view.getId()==android.R.id.content){//android:id="@android:id/content"
					return (ViewGroup) view;
				}
			}
			if(view!=null){
				ViewParent parent = view.getParent();
				view = parent instanceof View ?(View)parent:null;
			}
		}while(view!=null);
		return null;
	}

	public static FloatView makeMenu(View view, int resId){
		return new FloatView(view, resId);
	}

	public FloatView show(){
		//3.将菜单布局add到帧布局
		if(rootView.getParent()!=null){
			mParentVG.removeView(rootView);
    }
		LayoutParams lp =  new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);



		mParentVG.addView(rootView,lp);

		return this;
	}

	public void dismiss(){
		mParentVG.removeView(rootView);
		rootView = null;
	}
}